package cn.mw.cmdb.trigger;

import cn.hutool.core.date.DateUtil;
import cn.mw.components.mongodb.entity.SubCondition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class TriggerVariableManage {
    private ExpressionParser parser;

    private StandardEvaluationContext context;

    private Map<String ,String> keywordMap = new HashMap<>();

    public TriggerVariableManage(){
        this.parser = new SpelExpressionParser();
        this.context = new StandardEvaluationContext();

        try {
            this.context.registerFunction("addDays", DateUtil.class.getDeclaredMethod("offsetDay", java.util.Date.class, int.class));
        }catch (Exception e){
            log.error("TriggerVariableManage" ,e);
        }

        keywordMap.put("@currentDate" ,"new java.util.Date()");
        keywordMap.put("@beforeNum" ,"#mwCmdbNotify.getBeforeNum()");
    }

    public String resolve(SubCondition subCondition , MwCmdbNotify mwCmdbNotify){
        this.context.setVariable("mwCmdbNotify" ,mwCmdbNotify);
        String expression = subCondition.getValue().toString();
        for(Map.Entry<String ,String> entry:keywordMap.entrySet()){
            expression = expression.replaceAll(entry.getKey() ,entry.getValue());
        }
        Date result = parser.parseExpression(expression).getValue(context, java.util.Date.class);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return simpleDateFormat.format(result);
    }
}
